﻿#第十一章 正则表达式

import re

s = "abc\12";

reg = r"[a-z\0-9]"  #加r前缀不需要考虑转义问题

if re.match(reg,s):
	print("ok");
else:
	print("fail")
	
#正则拆分字符串

s = "a,b ,c;,d   ;,e"

print(re.split(r"[\s\;\,]+",s)) # \s 表示空白字符包括 : [空格\n\t\r\f\v]

#分组

reg=r"^(\d{3})-(\d{3,8})$"

reg = re.match(reg,"020-6849524")
print(reg)
print(reg.group(0)) #原始串
print(reg.group(1)) #第一组 以此类推
print(reg.groups()) #所有匹配的组 list

#预编译;对于一个重复多次利用的正则可以预编译

#Regular Expression
regObj = re.compile(r"^[1]\d{10}") 

print(regObj.match("13155487842").groups())


x = 1
def fn():
	global x
	x = 2	
	return x
	
print(x)
fn()
print(x)

def writeStr(url,content):
	with open(url,'w') as f:
		f.write(content)

longStr = "123 23 货物A 货物B 货物C 货物D 货物E 货物F 45 78 货物G 货物H 货物I 货物J 货物K 货物L"
regObj = re.compile(r"[\d+\s+]+") 

saveurl = "E:/zhh/mycode/python/learnpy/iofile/"
idx = -1
countIter = 0
fileFix = 'data'

itObj = regObj.finditer(longStr)
for i in itObj:
	print('for i=',i)
	posObj = i.span()
	matchStr = i.group() #得到匹配的串
	print('i.span',posObj,'matchStr=',matchStr)
	if re.search(r'\d',matchStr):
		if idx>-1:
			saveStr = longStr[idx:posObj[0]]
			countIter+=1
			writeStr(saveurl+fileFix+str(countIter)+'.txt',saveStr)
			print('saveStr=',saveStr)
		idx = posObj[0]
		print("..分割..idx=",idx)
countIter+=1
saveStr = longStr[idx:len(longStr)]
writeStr(saveurl+fileFix+str(countIter)+'.txt',saveStr)
print('longStr 最后=',saveStr,countIter)	
	
m1 = regObj.search(longStr)
print("m1=",m1.groups())

regObj2=re.compile(r'[\d+.*\d+]') # 点:'.'的含义是匹配任意非换行符,当开启了re.DOTALL模式的话也能匹配换行符
lst1 = regObj2.split(longStr)
lst2=regObj2.findall(longStr)
print(lst1)
print(lst2)


